package com.toocms.jinjuhang.ui.mine.payment

import android.app.Application
import android.os.Bundle
import androidx.databinding.ObservableArrayList
import androidx.databinding.ObservableField
import com.toocms.jinjuhang.R
import com.toocms.jinjuhang.BR
import com.toocms.jinjuhang.config.Constants
import com.toocms.jinjuhang.config.Urls
import com.toocms.jinjuhang.config.UserRepository
import com.toocms.jinjuhang.data.goods.GoodsListData
import com.toocms.jinjuhang.widget.view_model.requestData
import com.toocms.tab.base.BaseModel
import com.toocms.tab.base.BaseViewModel
import com.toocms.tab.binding.ItemBinding
import com.toocms.tab.binding.command.BindingAction
import com.toocms.tab.binding.command.BindingCommand
import com.toocms.tab.bus.event.SingleLiveEvent

class PaymentResultModel(application: Application,val bundle: Bundle?) : BaseViewModel<BaseModel>(application) {
    val pointsObservableField by lazy {
        val content = bundle?.getString(Constants.BundleKey.KEY_POINTS) ?: "0"
        ObservableField(content)
    }
    private var p = 1
    val recommendItems = ObservableArrayList<PaymentResultRecommendItemModel>()
    val recommendItemBinding = ItemBinding.of<PaymentResultRecommendItemModel>(
        BR.paymentResultRecommendItemModel,
        R.layout.item_payment_result_recommend
    )


    val stopLoadSingleLiveEvent = SingleLiveEvent<Unit>()
    val loadBindingCommand = BindingCommand<BindingAction>(BindingAction {
        p++
        pointGoods(p)
    })

    init {
        pointGoods(p, true)
    }

    //-------------------------------------------API------------------------------------------------

    private fun pointGoods(p: Int, isShowLoading: Boolean = false) {
        val params = mutableMapOf<String, String?>()
        params["member_id"] = UserRepository.user.member_id
        params["p"] = p.toString()
        requestData(
            Urls.Goods.POINT_GOODS,
            params,
            resultClass = GoodsListData::class.java,
            isShowLoading = isShowLoading,
            result = {
                if (1 == p) recommendItems.clear()
                it.list?.forEach {
                    recommendItems += PaymentResultRecommendItemModel(
                        this,
                        ObservableField(it)
                    )
                }
            },
            finish = {
                stopLoadSingleLiveEvent.call()
            })
    }
}